'use client';

import React, { useCallback, useRef } from 'react';
import clsx from 'clsx';
import toast from 'react-hot-toast';
import { FolderAddOutlined } from '@ant-design/icons';
import { FormFolder } from './FormFolder';
import { XMarkIcon } from '@heroicons/react/24/outline';
import { useSearchParams } from 'next/navigation';
import { createFolder } from 'src/actions/folder';
import type { FormFolderProps, Values } from './FormFolder';
import type { UseFormReturn } from 'react-hook-form';

export interface FuncNewFolderProps {
  className?: string;
  modalClassName?: string;
  onSuccess?: () => void;
}

function FuncNewFolderNoMemoized(props: FuncNewFolderProps) {
  const { className, modalClassName, onSuccess } = props;

  const searchParams = useSearchParams();
  const folderId = searchParams.get('folderId') ?? undefined;

  // Refs
  const dialog = useRef<HTMLDialogElement>(null);
  const formFolder = useRef<UseFormReturn<Values>>(null);

  // Handler
  const handleDialogClose = useCallback(() => {
    if (dialog.current) {
      dialog.current.close();
      formFolder.current?.reset();
    }
  }, []);

  const handleDialogOpen = useCallback(() => {
    if (dialog.current) {
      dialog.current.show();  // 不要用 showModal，否则会导致 dialog 被标为 top-layer 永远置为最上层, 任何元素都无法覆盖该元素
    }
  }, []);

  const handleSubmit = useCallback<NonNullable<FormFolderProps['onSubmit']>>(
    async (values) => {
      await createFolder({
        ...values,
        parentId: folderId,
      });
      toast.success('新建文件夹成功');
      handleDialogClose();
      onSuccess?.();
    },
    [folderId, handleDialogClose, onSuccess]
  );

  // Render
  return (
    <>
      <button
        type="button"
        className={clsx('btn btn-sm btn-ghost rounded-full text-base', className)}
        title="新建文件夹"
        onClick={handleDialogOpen}
      >
        <FolderAddOutlined />
      </button>
      <dialog ref={dialog} className={clsx('modal overflow-hidden', modalClassName)}>
        <div className="modal-box">
          <button
            className="btn btn-sm btn-circle btn-ghost absolute right-2 top-2"
            onClick={handleDialogClose}
          >
            <XMarkIcon className="size-4" />
          </button>
          <h3 className="font-bold text-lg">新建文件夹</h3>
          <div className="py-4">
            <FormFolder ref={formFolder} onSubmit={handleSubmit} />
          </div>
        </div>
      </dialog>
    </>
  );
}

export const FuncNewFolder = React.memo(FuncNewFolderNoMemoized);
